//
//  SearchBarView.m
//  Arts1
//
//  Created by lanou on 15/8/29.
//  Copyright (c) 2015年 Arts1. All rights reserved.
//

#import "SearchBarView.h"
#import "AllHeader.h"
#import "CourseModel.h"


#define  sCUrl @"http://arts1.dlab.com.cn/app/course"

@implementation SearchBarView

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor= [UIColor whiteColor];
        
        _searchBar = [[UISearchBar alloc] init];
        [_searchBar setFrame:(CGRectMake(2, 5, SCREEN_WIDTH - 4, 34))];
        _searchBar.searchBarStyle = UISearchBarStyleDefault;
        _searchBar.placeholder = @"search";
        _searchBar.delegate = self;
        _searchBar.showsCancelButton = NO;
        
        // UISearchBar 有两个的子视图有两个姿势图，一个是背景视图，一个是textfield
        [self addSubview:_searchBar];
        UIView *view = _searchBar.subviews[0];
        [view.subviews[0] removeFromSuperview];
        UITextField *textfield = (UITextField *)view.subviews[0];
        textfield.backgroundColor = kCustomColor(230, 230, 230, 1);
  
        for(id cc in [_searchBar subviews]){
            if([cc isKindOfClass:[UIButton class]]){
                UIButton *btn = (UIButton *)cc;
                [btn setTitle:@"C" forState:UIControlStateNormal];
            }  
        }
        [self createSearchResultView];
    }
    return self;
}

// 网络请求
- (void)requestSearchResults{
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    manage.responseSerializer.acceptableContentTypes  =[NSSet setWithObject:@"text/html"];
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSDictionary *paraDic = @{@"search":_search};
    
    [manage POST:sCUrl parameters:paraDic
         success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         // 请求成功的时候调用这个block
         NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableContainers) error:nil];
         //返回的状态
         int index = [dic[@"status"] intValue];
         if (index == 1) {
             NSArray *arr = dic[@"list"];
//             for (NSDictionary *dict in arr) {
//                 CourseCateModel *cate = [[CourseCateModel alloc] init];
//                 [cate setValuesForKeysWithDictionary:dict];
//                 [self.dataArr addObject:cate];
//             }
         }
         
         dispatch_async(dispatch_get_main_queue(), ^{
           //  [self.collectionview reloadData];
         });
         
         NSLog(@"课程分类返回数据 ： %@", dic);
         
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         // 请求失败的时候调用调用这个block
         NSLog(@"请求失败");
     }];
    
}

// 创建搜索结果展示视图
- (void)createSearchResultView{
    _resultView = [[UITableView alloc] initWithFrame:CGRectMake(0,SCREEN_WIDTH, 44, 0) style:(UITableViewStylePlain)];
    _resultView.delegate = self;
    _resultView.dataSource = self;
    [self addSubview:_resultView];
}

#pragma mark --- UISearchBarDelegate

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
   // self.frame = CGRectMake(0, 20, SCREEN_WIDTH, SCREEN_HEIGHT - 20);
    _resultView.frame = CGRectMake(0, 44, SCREEN_WIDTH, SCREEN_HEIGHT - 64);
    _searchBar.showsCancelButton = YES;
    return YES;
}

/**
*  点击搜索   请求搜索结果
*/
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    [_searchBar resignFirstResponder];
    _search = searchBar.text;
    [self requestSearchResults];
}

/**
 *  取消搜索
 */
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    [_searchBar resignFirstResponder];
    _searchBar.text = nil;
    self.frame = CGRectMake(0, 20, SCREEN_WIDTH, 44);
}



// called when search results button pressed
- (void)searchBarResultsListButtonClicked:(UISearchBar *)searchBar{
  self.frame = CGRectMake(0, 20, SCREEN_WIDTH, 44);
    

}

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{
    if (point.y > 64 && point.y < SCREEN_HEIGHT) {
        return _resultView;
    } else {
    return [super hitTest:point withEvent:event];
    }
}

# pragma mark ---- UITableViewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SearchCourse"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"SearchCourse"];
    }
    CourseModel *model = (CourseModel *)_dataArr[indexPath.row];
    cell.textLabel.text = model.title;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    CourseModel *model = (CourseModel *)_dataArr[indexPath.row];
    
}


/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
